package com.jtpay.sdk.jtpay;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import com.jtpay.sdk.jtpay.utils.PayFileUtil;
import com.jtpay.sdk.jtpay.utils.PayInstallUtil;
import com.jtpay.sdk.jtpay.utils.PayLogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class PayPluginManager {
    private static Context mContext;
    private PayInstallUtil installUtil;
    private final String PLUGIN_NAME = "PayPlugin.apk";
    private final String PACKAGE_NAME = "com.pay.sdk";
    private static String FILE;
    private static PayPluginManager pluginManager;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private PayPluginManager(Context context) {
        mContext = context;
        installUtil = new PayInstallUtil(context);
        FILE = Environment.getExternalStorageDirectory() + File.separator + mContext.getPackageName() + File.separator + PLUGIN_NAME;
    }

    public static synchronized PayPluginManager getInstance(Context context) {
        if (pluginManager == null) {
            synchronized (PayPluginManager.class) {
                if (pluginManager == null) {
                    pluginManager = new PayPluginManager(context);
                }
            }
        }
        return pluginManager;
    }

    private void installPayPlugin(final String path, String packageName, Activity activity) {
        if (installUtil.checkApkExist(packageName))
            return;
        if (Build.VERSION.SDK_INT >= 23) {
            verifyStoragePermissions(activity);
        } else {
            assetsToSD(FILE);
            installUtil.installApk(FILE);
        }
    }

    public void installPayPlugin(Activity activity) {
        installPayPlugin(FILE, PACKAGE_NAME, activity);
    }

    private void assetsToSD(String path) {
        InputStream is = null;
        AssetManager assetManager = null;
        FileOutputStream out = null;
        try {
            PayLogUtil.log("installPayPlugin path = " + path);
            assetManager = mContext.getAssets();
            is = assetManager.open(PLUGIN_NAME);
            File fileOut = new File(path);
            if (fileOut.exists()) {
                fileOut.delete();
            }
            PayFileUtil.copyToFile(is, fileOut);
        } catch (IOException e) {
            PayLogUtil.log("assetsToSD error");
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getFILE() {
        return FILE;
    }

    public boolean isInstalled() {
        return installUtil.checkApkExist(PACKAGE_NAME);
    }

    public void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        } else {
            assetsToSD(FILE);
            installUtil.installApk(FILE);
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            assetsToSD(FILE);
            installUtil.installApk(FILE);
        } else {
            // Permission Denied
            Toast.makeText(mContext, "You rejected the SD card authority, WeChat will not be able to pay the normal use of", Toast.LENGTH_SHORT).show();
        }
    }
}
